import { useAppSelector } from "@/store";
import { selectUserSysMenus } from "@/store/slice/app";
import { Breadcrumb } from "antd";
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";

type BreadcrumbType = {
  title: string;
  href?: string;
};

function ProBreadcrumb() {
  const [extraBreadcrumbItems, setExtraBreadcrumbItems] = useState<
    BreadcrumbType[]
  >([]);
  const menus = useAppSelector(selectUserSysMenus);
  const location = useLocation();
  const pathname = location.pathname;

  useEffect(() => {
    let breadcrumbNameMap = new Map();
    menus.forEach((item) => {
      breadcrumbNameMap.set(item.url, item.name);
    });
    getBreadCrumb(breadcrumbNameMap);
  }, [menus]);

  function getBreadCrumb(breadcrumbNameMap: any) {
    let list: BreadcrumbType[] = [];
    const pathSnippets = pathname.split("/").filter((i) => i);
    pathSnippets.map((item, index) => {
      let url = `/${pathSnippets.slice(0, index + 1).join("/")}`;
      const i = {} as BreadcrumbType;
      if (url === pathname) {
        i.href = url;
      }
      i.title = breadcrumbNameMap.get(url);
      list.push(i);
    });
    setExtraBreadcrumbItems(list);
  }

  return (
    <Breadcrumb
      style={{ margin: "16px 0" }}
      items={extraBreadcrumbItems}
    ></Breadcrumb>
  );
}
export default ProBreadcrumb;
